<template>
  <div class="notification-center">
    <div class="notification-header">
      <h3>通知中心</h3>
      <div class="notification-tabs">
        <div 
          v-for="tab in tabs" 
          :key="tab.type" 
          :class="['tab', { active: activeTab === tab.type }]"
          @click="activeTab = tab.type"
        >
          {{ tab.name }}
        </div>
      </div>
      <div class="notification-actions">
        <button @click="markAllAsRead" class="mark-all-read">全部标为已读</button>
      </div>
    </div>
    
    <div class="notification-list">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="filteredNotifications.length === 0" class="empty-state">
        暂无通知
      </div>
      <div v-else>
        <div 
          v-for="notification in filteredNotifications" 
          :key="notification.id" 
          :class="['notification-item', { 'unread': !notification.isRead }]"
          @click="markAsRead(notification.id)"
        >
          <div class="notification-avatar">
            <img :src="getAvatar(notification.senderId)" alt="头像">
          </div>
          <div class="notification-content">
            <div class="notification-message">
              {{ formatNotificationContent(notification) }}
            </div>
            <div class="notification-time">
              {{ formatTime(notification.createTime) }}
            </div>
          </div>
        </div>
        <div v-if="hasMore" class="load-more" @click="loadMore">
          加载更多
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import axios from 'axios';

// 通知类型
const TYPE_LIKE = 1;
const TYPE_COMMENT = 2;
const TYPE_FOLLOW = 3;

// 状态变量
const notifications = ref([]);
const loading = ref(false);
const page = ref(1);
const size = ref(10);
const hasMore = ref(true);
const activeTab = ref('all');
const tabs = [
  { type: 'all', name: '全部' },
  { type: TYPE_LIKE, name: '点赞' },
  { type: TYPE_COMMENT, name: '评论' },
  { type: TYPE_FOLLOW, name: '关注' }
];

// 获取当前登录用户ID
const getUserId = () => {
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    return JSON.parse(userInfo).id;
  }
  return null;
};

// 根据当前选中的标签过滤通知
const filteredNotifications = computed(() => {
  if (activeTab.value === 'all') {
    return notifications.value;
  }
  return notifications.value.filter(notification => notification.type === activeTab.value);
});

// 获取通知列表
const fetchNotifications = async (reset = false) => {
  const userId = getUserId();
  if (!userId) return;
  
  loading.value = true;
  
  try {
    if (reset) {
      page.value = 1;
      notifications.value = [];
    }
    
    let url = `/notifications/user/${userId}`;
    if (activeTab.value !== 'all') {
      url = `/notifications/user/${userId}/type/${activeTab.value}`;
    }
    
    const response = await axios.get(url, {
      params: {
        page: page.value,
        size: size.value
      }
    });
    
    const newNotifications = response.data;
    
    if (reset) {
      notifications.value = newNotifications;
    } else {
      notifications.value = [...notifications.value, ...newNotifications];
    }
    
    hasMore.value = newNotifications.length === size.value;
    page.value++;
  } catch (error) {
    console.error('获取通知失败:', error);
  } finally {
    loading.value = false;
  }
};

// 标记通知为已读
const markAsRead = async (notificationId) => {
  const userId = getUserId();
  if (!userId) return;
  
  try {
    await axios.put(`/notifications/${notificationId}/read`, null, {
      params: { userId }
    });
    
    // 更新本地通知状态
    const notification = notifications.value.find(n => n.id === notificationId);
    if (notification) {
      notification.isRead = true;
    }
  } catch (error) {
    console.error('标记通知已读失败:', error);
  }
};

// 标记所有通知为已读
const markAllAsRead = async () => {
  const userId = getUserId();
  if (!userId) return;
  
  try {
    await axios.put(`/notifications/user/${userId}/read-all`);
    
    // 更新本地通知状态
    notifications.value.forEach(notification => {
      notification.isRead = true;
    });
  } catch (error) {
    console.error('标记所有通知已读失败:', error);
  }
};

// 加载更多通知
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    fetchNotifications();
  }
};

// 格式化通知内容
const formatNotificationContent = (notification) => {
  switch (notification.type) {
    case TYPE_LIKE:
      return `用户 ${notification.senderId} 赞了你的动态`;
    case TYPE_COMMENT:
      return `用户 ${notification.senderId} 评论了你的${notification.resourceType === 1 ? '动态' : '评论'}`;
    case TYPE_FOLLOW:
      return `用户 ${notification.senderId} 关注了你`;
    default:
      return notification.content || '收到一条新通知';
  }
};

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return '';
  
  const date = new Date(timeStr);
  const now = new Date();
  const diff = now - date;
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚';
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`;
  }
  
  // 小于24小时
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`;
  }
  
  // 小于30天
  if (diff < 30 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`;
  }
  
  // 大于30天
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
};

// 获取用户头像
const getAvatar = (userId) => {
  // 这里可以根据实际情况获取用户头像
  return `https://placehold.co/40x40`;
};

// 监听标签变化，重新加载通知
watch(activeTab, () => {
  fetchNotifications(true);
});

// 组件挂载时加载通知
onMounted(() => {
  fetchNotifications();
});
</script>

<style scoped>
.notification-center {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-height: 500px;
  display: flex;
  flex-direction: column;
}

.notification-header {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.notification-header h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 600;
}

.notification-tabs {
  display: flex;
  margin-bottom: 10px;
}

.tab {
  padding: 4px 12px;
  margin-right: 8px;
  cursor: pointer;
  border-radius: 16px;
  font-size: 14px;
  transition: all 0.3s;
}

.tab:hover {
  background-color: #f5f5f5;
}

.tab.active {
  background-color: #e6f7ff;
  color: #1890ff;
}

.notification-actions {
  display: flex;
  justify-content: flex-end;
}

.mark-all-read {
  background: none;
  border: none;
  color: #1890ff;
  cursor: pointer;
  font-size: 14px;
  padding: 4px 8px;
}

.mark-all-read:hover {
  text-decoration: underline;
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  padding: 0;
}

.notification-item {
  display: flex;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: #f5f5f5;
}

.notification-item.unread {
  background-color: #e6f7ff;
}

.notification-avatar {
  margin-right: 12px;
}

.notification-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.notification-content {
  flex: 1;
}

.notification-message {
  font-size: 14px;
  margin-bottom: 4px;
}

.notification-time {
  font-size: 12px;
  color: #999;
}

.loading, .empty-state {
  padding: 20px;
  text-align: center;
  color: #999;
}

.load-more {
  padding: 12px;
  text-align: center;
  color: #1890ff;
  cursor: pointer;
}

.load-more:hover {
  background-color: #f5f5f5;
}
</style>